package com.aifast.common.fieldEncrypt;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import com.aifast.common.global.Const;
import org.springframework.stereotype.Service;

/**
 * @Author fujian
 * @since 2022/9/12 15:35
 */
@Service
public class AiEncryptorImpl implements AiEncryptor {

    private final static byte[] default_key = "8mf6dsjidxk23jar".getBytes();

    @Override
    public String encrypt(Object value, Algorithm algorithm, String key) {
        if(ObjectUtil.isNull(value)){
            return Const.EMPTY;
        }
        String result = null;
        byte[] bytes = getKey(key);
        String toStr = Convert.toStr(value);
        switch (algorithm){
            case AES:
                result = SecureUtil.aes(bytes).encryptHex(toStr);
                break;
            case RSA:
                result = SecureUtil.rsa().encryptHex(toStr,KeyType.PublicKey);
                break;
            case SM4:
                result = SmUtil.sm4(bytes).encryptHex(toStr);
                break;
            case BASE64:
                result = Base64.encode(toStr);
                break;
            case MD5_16:
                result = SecureUtil.md5(toStr);
                break;
        }

        return result;
    }

    @Override
    public String decrypt(Object value, Algorithm algorithm, String key) {
        if(ObjectUtil.isNull(value)){
            return Const.EMPTY;
        }
        String result = null;
        byte[] bytes = getKey(key);
        String toStr = Convert.toStr(value);
        switch (algorithm){
            case AES:
                result = SecureUtil.aes(bytes).decryptStr(toStr);
                break;
            case RSA:
                result = SecureUtil.rsa().decryptStr(toStr,KeyType.PrivateKey);
                break;
            case SM4:
                result = SmUtil.sm4(bytes).decryptStr(toStr);
                break;
            case BASE64:
                result = Base64.decodeStr(toStr);
                break;

        }
        return result;
    }


    private static byte[] getKey(String key){
        if(StrUtil.isBlank(key)){
            return default_key;
        }
        return key.getBytes();
    }

}
